<?php

namespace App\Http\Controllers\merchant;

use App\Http\Controllers\Controller;
use App\Models\Mysql\XnMechantInvoicing;
use App\Models\Mysql\XnMechantOrderInvocingRelation;
use App\Models\Mysql\XnMechantOrderInvoicing;
use App\Models\Mysql\XnMerchant;
use App\Models\Mysql\XnOrder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class MerchantInvoiceController extends Controller
{
    public function invoicingslist(Request $request){
            $mechant_number = $request->post('mechant_number');
            $infos = XnMechantInvoicing::where('mechant_number',$mechant_number) -> first() ;
            if(empty($infos)){
                return $this -> sendError( '未查询到数据');
            }
            $infos =$infos -> toArray();
        return $this -> sendResponse($infos,'成功');
    }

    public function addinvoicings(Request $request){
            $infos= $request-> post();
            $info = XnMechantInvoicing::where('mechant_number',$infos['mechant_number']) -> exists();
            $mechant_info = XnMerchant:: where('Merchant_number',$infos['mechant_number']) -> select('name','Nickname') -> first() -> toArray();
            $data = [
                'Enterprise_Name'=>$infos['Enterprise_Name'],
                'Identification_Number'=>$infos['Identification_Number'],
                'Business_Address'=>$infos['Business_Address'],
                'Phone'=>$infos['Phone'],
                'Bank_Deposit'=>$infos['Bank_Deposit'],
                'Bank_Accont'=>$infos['Bank_Accont'],
                'Email_Person'=>$infos['Email_Person'],
                'Email_Address'=>$infos['Email_Address'],
                'Email_phone'=>$infos['Email_phone'],
                'mechant_number'=>$infos['mechant_number'],
                'ctime'=>date('Y-m-d H:i:s',time()),
                'mechant_name'=>$mechant_info['name'],
                'nick_name'=>$mechant_info['Nickname']
            ];
            if(!$info){
                XnMechantInvoicing::insert($data);
                return $this -> sendResponse([], '添加成功');
            }else{
                unset($data['mechant_number']);
                unset($data['ctime']);
                XnMechantInvoicing::where('mechant_number','=',$infos['mechant_number'])->update($data);
                return $this -> sendResponse([], '修改成功');
            }
    }

    public function invoicingsrecordlist(Request $request){
            $begintime =$request-> post('begintime','');
            $endtime =$request-> post('endtime','');
            $condition[] = ['time','>=',$begintime];
            $condition[] = ['time','<=',$endtime];
            $status = $request -> post('invoicing_status','');
            if(!empty($status)){
                $condition[]  = ['invoicing_status','=',$status];  // 1.审核中 2.开票成功
            }
            $mechant_number = $request -> post('mechant_number','');
            $condition[] = ['mechant_number','=',$mechant_number];
            $res = XnMechantOrderInvoicing::where($condition)
                -> select('id','all_money','invoicing_time','invoicing_status','time')
                -> orderBy('time','desc')
                -> paginate(8);
            if(!$res){
                return $this -> sendError('未查询到数据');
            }
            return $this -> sendResponse($res,'');
    }

    public function invoicingsorderlist(Request $request){
            $id = $request-> post('in_id','');
            $goods_name = $request -> post('goods_name','');
            $order_no = $request -> post('order_no','');
            // 订单关联数据
            $relationorder = XnMechantOrderInvocingRelation::where('in_id','=',$id) -> pluck('o_id') -> toArray();
            //print_r($relationorder);
            $condition = [];
            if(!empty($goods_name)){
                $condition[] = ['goodsName','like','%'.$goods_name.'%'];
            }
            if(!empty($order_no)){
                $condition[] = ['orderNum','=',$order_no];
            }
            //$order_id = implode(',',$relationorder);
            //$condition[] = ['id','in',$relationorder];
            // 订单信息
            $orderinfos = XnOrder::where($condition)
                -> wherein('id',$relationorder)
                -> orderBy('recharge_time','desc')
                -> select('recharge_time','order_sn','goods_name','account','price','unitPrice','goods_num','all_money','recharge_status')
                -> paginate(8)
                -> toArray();
           // print_r($orderinfos);
        return $this -> sendResponse($orderinfos,'');
    }

    public function getcontentorder(Request $request){
            $id = $request -> post('in_id');
            $goods_name = $request -> post('goods_name');
            $order_no =$request -> post('order_no');
            // 订单关联数据
            $relationorder = XnMechantOrderInvocingRelation::where('in_id',$id) -> pluck('o_id');
        $condition = [];
            if(!empty($goods_name)){
                $condition[] = ['goodsName','like','%'.$goods_name.'%'];
            }
            if(!empty($order_no)){
                $condition[] = ['orderNum','=',$order_no];
            }


            $orderinfos = XnOrder:: where($condition)
                -> wherein('id',$relationorder)
                -> selectRaw('count(id) as all_count,sum(all_money) as allmoney')
                -> first()
                -> toArray();
            $data['order_num'] = $orderinfos['all_count'];
            $data['order_money'] = $orderinfos['allmoney'];
        return $this -> sendResponse($data,'');
    }

    public function caninvoicingorderinfo(Request $request){
            $goods_name = $request -> post('good_name','');
            $begintime = $request -> post('begintime','');
            $endtime = $request -> post('endtime','');
            $goodsId = $request -> post('order_num','');
            $merchant_number = $request -> post('merchant_number','');
            $order_arrs = XnMechantOrderInvocingRelation::where('mechant_number','=',$merchant_number) -> pluck('o_id');
            $condition[]  = ['recharge_time', '>=', $begintime];
            $condition[]  = ['recharge_time', '<=', $endtime];

            $condition[] = ['Merchant_number','=',$merchant_number];
            if(!empty($goodsId)){
                $condition[] = ['gid','=',$goodsId];
            }
            if(!empty($goods_name)){
                $condition[] = ['goods_name','like','%'.$goods_name.'%'];
            }
            $condition[] = ['recharge_status','=',1];
            if(!empty($order_arrs)){
                $select = 'count(IF(recharge_status = 1,1,NULL)) as successorder,count(IF(recharge_status = 2,1,NULL)) as failsorder,sum(IF(recharge_status = 1,all_money,null)) as successmoney,sum(if(recharge_status = 2,all_money,null)) as failsmoney';
                $res = XnOrder:: where($condition)
                    ->whereNotIn('id',$order_arrs)
                    -> selectRaw($select)
                    -> first()
                    -> toArray();
                $order_info =XnOrder:: where($condition) -> whereNotIn('id',$order_arrs)-> pluck('id');
            }else{
                $order_info =XnOrder:: where($condition) -> pluck('id');
                $select = 'count(IF(recharge_status = 1,1,NULL)) as successorder,count(IF(recharge_status = 2,1,NULL)) as failsorder,sum(IF(recharge_status = 1,rechargeMoney,null)) as successmoney,sum(if(recharge_status = 2,rechargeMoney,null)) as failsmoney';
                $res = XnOrder:: where($condition)
                    -> selectRaw($select)
                    -> first()
                    -> toArray();
            }
            if($res['successorder'] == 0 && $res['failsorder']==0 && $res['successmoney']==0 && $res['failsmoney']==0 ){
                return  $this -> sendError('暂无数据');
            }
            $data = [
                'successorder'=>$res['successorder'],
                'failsorder'=>$res['failsorder'],
                'successmoney'=>$res['successmoney'],
                'failsmoney'=>$res['failsmoney'],
                'order_id'=>$order_info
            ];
        return $this -> sendResponse($data,'');
    }

    //  订单开发票
    public function invoicingorders(Request $request){
            $all_money = $request -> post('all_money');
            $all_count = $request -> post('all_count');
            $order_id = $request -> post('order_id');
            $mechant_number = $request -> post('mechant_number');
            $start_time = $request -> post('start_time');
            $end_time = $request -> post('end_time');
            $time = date('Y-m-d H:i:s',time());
            $order_id_arr = explode(',',$order_id);
            $invocing_time = $start_time.'至'.$end_time;
            $mechant_invocing_info = XnMechantInvoicing::where('mechant_number','=',$mechant_number) -> first() -> toArray();
            $invocing_info = [
                'time'=>$time,
                'all_money'=> $all_money,
                'all_count'=> $all_count,
                'invoicing_time'=>$invocing_time,
                'invoicing_status'=> 1,
                'mechant_number'=>$mechant_number,
                'mechant_name'=>$mechant_invocing_info['mechant_name'],
                'nick_name'=>$mechant_invocing_info['Enterprise_Name'],
                'Identification_Number'=>$mechant_invocing_info['Identification_Number'],
                'phone'=>$mechant_invocing_info['Phone'],
                'Bank_Deposit'=>$mechant_invocing_info['Bank_Deposit'],
                'Bank_Accont'=>$mechant_invocing_info['Bank_Accont'],
                'Email_Person'=>$mechant_invocing_info['Email_Person'],
                'Email_Address'=>$mechant_invocing_info['Email_Address'],
                'Email_phone'=>$mechant_invocing_info['Email_phone'],
                'Business_Address'=>$mechant_invocing_info['Business_Address']
            ];
            // 启动事务
        DB::connection(request()->get('db', 'supplier'))->beginTransaction();
            try{
                $inc_id = XnMechantOrderInvoicing::insertGetId($invocing_info);
                if($all_count == 1){
                    $money = XnOrder:: where('id','=',$order_id) -> value('all_money');
                    $relation_arr = [
                        'in_id'=>$inc_id,
                        'o_id'=>$order_id,
                        'ctime'=>$time,
                        'money'=>$money,
                        'mechant_number'=>$mechant_number
                    ];
                    XnMechantOrderInvocingRelation::insert($relation_arr);
                }else if($all_count > 1){
                    foreach($order_id_arr as $k=>$v){
                        $money = XnOrder:: where('id',$v) -> value('all_money');
                        $relation_arr[] = [
                            'in_id'=>$inc_id,
                            'o_id'=>$v,
                            'ctime'=>$time,
                            'money'=>$money,
                            'mechant_number'=>$mechant_number
                        ];
                    }
                    XnMechantOrderInvocingRelation::insert($relation_arr);
                }
                // 提交事务
                DB::connection(request()->get('db', 'supplier'))->commit();
                return  $this -> sendResponse([],'开票成功');
            } catch (\Exception $e) {
                // 回滚事务
                DB::connection(request()->get('db', 'supplier'))->rollback();
                return  $this -> sendError('开票失败');
            }

    }
}
